package com.gomtel.smartdevice.ui.activity.tools;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.gomtel.smartdevice.R;
import com.gomtel.smartdevice.api.MessageManager;
import com.gomtel.smartdevice.base.WatchAppBaseActivity;
import com.gomtel.smartdevice.bean.UserContent;
import com.gomtel.smartdevice.bt.bt.BluetoothChatService;
import com.gomtel.smartdevice.bt.bt.Constants;
import com.gomtel.smartdevice.global.DataClass;
import com.gomtel.smartdevice.global.WatchApplication;
import com.gomtel.smartdevice.moudle.db.entity.AppConfigurationInfo;
import com.gomtel.smartdevice.moudle.db.entity.AtrialFibrillationInfo;
import com.gomtel.smartdevice.moudle.event.CommonEvent;
import com.gomtel.smartdevice.moudle.event.EventCode;
import com.gomtel.smartdevice.moudle.rxtools.EventBusUtil;
import com.gomtel.smartdevice.ui.dialog.ProgressDialog;
import com.gomtel.smartdevice.ui.dialog.ShowDialog;
import com.gomtel.smartdevice.ui.view.MyProgress;
import com.gomtel.smartdevice.utils.ChartUtils;
import com.gomtel.smartdevice.utils.CommonUtils;
import com.gomtel.smartdevice.utils.LogUtil;
import com.gomtel.smartdevice.view.HeartBeatView;
import com.gomtel.smartdevice.widget.CalenderUtilsClass;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/8/6 0006.
 */

public class AtrialFibrillationActivity extends WatchAppBaseActivity implements View.OnClickListener {

    @BindView(R.id.img_btn_black)
    ImageButton img_btn_black;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.title_about)
    ImageButton title_about;

    @BindView(R.id.egc_layout)
    LinearLayout egc_layout;
    @BindView(R.id.egc)
    HeartBeatView egc;
    @BindView(R.id.stop)
    Button stop;

    @BindView(R.id.progress)
    MyProgress progress;

    @BindView(R.id.title_content_x)
    TextView title_content_x;
    @BindView(R.id.pvh_mmHg)
    TextView pvh_mmHg;
    @BindView(R.id.title_content_y)
    TextView title_content_y;
    @BindView(R.id.ldo_mmHg)
    TextView ldo_mmHg;

    @BindView(R.id.chart_line)
    LineChart chart;


    private List<String> intervalDate;
    private List<String> intervalSplitDate = new ArrayList<>();
    private List<Integer> atrialFibrillationHashMap = new ArrayList<>();
    private List<Integer> heartStatusHashMap = new ArrayList<>();
    private ChartUtils chartUtils;
    private String lastAtrialFibrillationContent = "--";
    private String lastHertContent = "--";
    private String recentlyTime = "--";
    private boolean checkStatus = false; // 按钮状态
    private boolean messageReadStatus = false; //图形回调状态

    private int ss;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (progress != null) {
                        progress.setProgress(ss);
                    }
                    break;
                case 1:
                    ss = getResources().getInteger(R.integer.measure_time_fc);
                    if (progress != null) {
                        progress.setProgress(ss);
                        messageReadStatus = false;
                        checkStatus = false;
                        insertDataOrQueryAtrialFibrillationData();
                        stop.setText(getString(R.string.begin));
                        Log.e(TAG, "设置成功");
                    }
                    break;
            }
            return true;
        }
    });
    private ShowDialog showDialog;
    private ProgressDialog progressDialog;
    private ProgressDialog mConProgressDialog;

    @Override
    protected void registerEvent(CommonEvent commonevent) {

    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_atrial_fibrillation;
    }

    @Override
    protected void initClass() {
        chartUtils = new ChartUtils();
        chartUtils.setAtrialFibrillationChart(chart);
        showDialog = ShowDialog.newInstance();
        progressDialog = showDialog.showProgressStatus(this, "准备中测试...");
        mConProgressDialog = showDialog.showProgressStatus(this, "正在连接心电测试...");
        mConProgressDialog.setCancelable(false);
        //mConProgressDialog.show();
    }

    @Override
    protected void initData() {
        ss = getResources().getInteger(R.integer.measure_time_fc);
        intervalDate = CalenderUtilsClass.getIntervalDate();
        intervalDate.add(CalenderUtilsClass.getCurrentDay(false));
        for (int i = 0; i < intervalDate.size(); i++) {
            String[] split = intervalDate.get(i).split("-");
            intervalSplitDate.add(split[1] + "/" + split[2]);
        }
        insertDataOrQueryAtrialFibrillationData();
    }

    @Override
    protected void initView() {
        egc_layout.setVisibility(View.VISIBLE);
        title_about.setVisibility(View.VISIBLE);
        title_name.setText(getString(R.string.atrial_fibrillation));
        title_content_x.setText(R.string.atrial_fibrillation);
        title_content_y.setText(R.string.HeartRate);
        stop.setText(getString(R.string.begin));
    }

    @Override
    protected void initListener() {
        img_btn_black.setOnClickListener(this);
        title_about.setOnClickListener(this);
        stop.setOnClickListener(this);
        AtrialFibrillationListener();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_btn_black:
                finish();
                break;
            case R.id.title_about:
                Intent intent = new Intent(AtrialFibrillationActivity.this, SignsOfHistoryActivity.class);
                intent.putExtra("ActionType", "2");
                startActivity(intent);
                break;
            case R.id.stop:
                if (!DataClass.onlineStatus) {
                    toastUtil.showToast("设备未连接 ... ");
                    return;
                }
                if (isCollection[0] && count <= 3) {
                    CommonUtils.showToast(getApplicationContext(), "数据正在加载中,请稍后");
                    return;
                }
                if (!checkStatus) {
                    progressDialog.show();
                    EventBusUtil.sendEvent(new CommonEvent(EventCode.AF_MEASURE));
                    stop.setText(getString(R.string.stop));
                    sendToAtrialFibrillationSetting();
                } else {
                    stop.setText(getString(R.string.begin));
                }
                checkStatus = !checkStatus;
                timeKeeping();

//                dataManager.insertAtrialFibrillationInfo(new AtrialFibrillationInfo(UserContent.UserName, CalenderUtilsClass.getCurrentDay(false), String.valueOf(0), String.valueOf(122)));
//                dataManager.insertAtrialFibrillationInfo(new AtrialFibrillationInfo(UserContent.UserName, CalenderUtilsClass.getCurrentDay(false), String.valueOf(2), String.valueOf(122)));
//                dataManager.insertAtrialFibrillationInfo(new AtrialFibrillationInfo(UserContent.UserName, CalenderUtilsClass.getCurrentDay(false), String.valueOf(1), String.valueOf(122)));
//                dataManager.insertAtrialFibrillationInfo(new AtrialFibrillationInfo(UserContent.UserName, CalenderUtilsClass.getCurrentDay(false), String.valueOf(1), String.valueOf(122)));
//                handler.sendEmptyMessage(1);
                break;
        }
    }

    //计时器
    public void timeKeeping() {
        if (!checkStatus) {
            handler.sendEmptyMessage(1);
            return;
        }
        WatchApplication.executorService.submit(() -> {
            try {
                Thread.sleep(1000);
                if (messageReadStatus) {
                    handler.sendEmptyMessage(0);
                    ss--;
                }
                if (!DataClass.onlineStatus) {
                    EventBusUtil.sendEvent(new CommonEvent(EventCode.LOCAL_AREA_LINKS));
                }
                if (ss > 0) {
                    timeKeeping();
                } else {
                    handler.sendEmptyMessage(1);
                    /*if (DataClass.onlineStatus) {
                        toastUtil.showToast("测量成功");
                    } else {
                        toastUtil.showToast("测量失败");
                    }*/
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    //数据插入更新
    private void insertDataOrQueryAtrialFibrillationData() {
        atrialFibrillationHashMap.clear();
        heartStatusHashMap.clear();
        List<AtrialFibrillationInfo> atrialFibrillationAllInfos = dataManager.queryAtrialFibrillationALLInfo(UserContent.UserName);
        if (atrialFibrillationAllInfos != null && atrialFibrillationAllInfos.size() > 0) {
            for (String day : intervalDate) {
                int atrialFibrillationStatusIndex = 0;
                int heartRateStatusIndex = 0;
                List<AtrialFibrillationInfo> atrialFibrillationInfosList = dataManager.queryAtrialFibrillationInfo(day);
                if (atrialFibrillationInfosList != null) {
                    for (AtrialFibrillationInfo atrialFibrillationInfo : atrialFibrillationInfosList) {
                        if (atrialFibrillationInfo != null) {
                            if ("2".equals(atrialFibrillationInfo.getAtrialFibrillationStatus()))
                                atrialFibrillationStatusIndex = atrialFibrillationStatusIndex + 1;
                            if ("1".equals(atrialFibrillationInfo.getAtrialFibrillationStatus()))
                                heartRateStatusIndex = heartRateStatusIndex + 1;
                            lastAtrialFibrillationContent = atrialFibrillationInfo.getAtrialFibrillationStatus();
                            lastHertContent = atrialFibrillationInfo.getHeartRateStatus();
                            recentlyTime = atrialFibrillationInfo.getRecentlyTime();
                        }
                    }
                    atrialFibrillationHashMap.add(atrialFibrillationStatusIndex);
                    heartStatusHashMap.add(heartRateStatusIndex);
                } else {
                    atrialFibrillationHashMap.add(0);
                    heartStatusHashMap.add(0);
                }
            }
            lastAtrialFibrillationContent = atrialFibrillationAllInfos.get(atrialFibrillationAllInfos.size() - 1).getAtrialFibrillationStatus();
            lastHertContent = atrialFibrillationAllInfos.get(atrialFibrillationAllInfos.size() - 1).getHeartRateStatus();
            recentlyTime = atrialFibrillationAllInfos.get(atrialFibrillationAllInfos.size() - 1).getRecentlyTime();
        } else {
            for (String day : intervalDate) {
//                dataManager.insertAtrialFibrillationInfo(new AtrialFibrillationInfo(UserContent.UserName, day, "疑似房颤", "40"));
                atrialFibrillationHashMap.add(0);
                heartStatusHashMap.add(0);
            }
        }

        loadMulticlassLineChartData(chart, atrialFibrillationHashMap, heartStatusHashMap, intervalSplitDate);
        if ("0".equals(lastAtrialFibrillationContent)) {
            pvh_mmHg.setText("正常");
        } else if ("1".equals(lastAtrialFibrillationContent)) {
            pvh_mmHg.setText("心率不齐");
        } else if ("2".equals(lastAtrialFibrillationContent)) {
            pvh_mmHg.setText("疑似房颤");
        }
        ldo_mmHg.setText(lastHertContent);
        progress.setText("近期测量:" + recentlyTime);
    }

    //折线图
    private void loadMulticlassLineChartData(final LineChart chart, List<Integer> index, List<Integer> index2, List<String> xAxisShowLable) {
        chart.setNoDataText("暂无数据");
        ArrayList<LineDataSet> allLinesList = new ArrayList<>();
        ArrayList<Entry> entryList = new ArrayList<>();
        ArrayList<Entry> entryList2 = new ArrayList<>();
        for (int i = 0; i < index.size(); i++) {
            entryList.add(new Entry(index.get(i), i));
        }
        for (int i = 0; i < index2.size(); i++) {
            entryList2.add(new Entry(index2.get(i), i));
        }
        //LineDataSet可以看做是一条线
        LineDataSet dataSet = new LineDataSet(entryList, "dataLine");
        dataSet.setLineWidth(0.5f);
        dataSet.setCircleSize(2f);// 显示的圆形大小
        dataSet.setDrawValues(false); // 隐藏折线图每个数据点的值
        dataSet.setValueTextColor(getResources().getColor(R.color.color_fatigue_orange_2));
        dataSet.setDrawCubic(false);//允许设置平滑曲线
        dataSet.setCircleColor(getResources().getColor(R.color.color_fatigue_orange_2));
        dataSet.setCircleColorHole(getResources().getColor(R.color.color_fatigue_orange_2));
        dataSet.setColor(getResources().getColor(R.color.color_fatigue_orange_2));
        dataSet.setDrawFilled(false);//是否填充折线下方

        LineDataSet dataSet2 = new LineDataSet(entryList2, "dataLine2");
        dataSet2.setLineWidth(0.5f);
        dataSet2.setCircleSize(2f);// 显示的圆形大小
        dataSet2.setDrawValues(false); // 隐藏折线图每个数据点的值
        dataSet2.setValueTextColor(getResources().getColor(R.color.red_style));
        dataSet2.setDrawCubic(false);//允许设置平滑曲线
        dataSet2.setCircleColor(getResources().getColor(R.color.red_style));
        dataSet2.setCircleColorHole(getResources().getColor(R.color.red_style));
        dataSet2.setColor(getResources().getColor(R.color.red_style));
        dataSet2.setDrawFilled(false);//是否填充折线下方

        allLinesList.add(dataSet);
        allLinesList.add(dataSet2);

        LineData mChartData = new LineData(xAxisShowLable, allLinesList);
        chart.setData(mChartData);
        // 设置动画
        chart.setVisibleXRangeMaximum(entryList.size() + 3);
        chart.setVisibleXRangeMinimum(entryList.size());
        chart.animateY(2000);
    }

    private boolean isSend = false;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 200) {
            if (!isSend) {
                isSend = true;
                CommonUtils.getHandler().postDelayed(this::sendToAtrialFibrillationSetting, 1000);
            }
        }
    }

    @Override
    protected void onRestart() {
        isSend = false;
        super.onRestart();
    }

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        super.onResume();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.BLUETOOTH_ADMIN}, 200);
        } else {
            if (!isSend) {
                isSend = true;
                CommonUtils.getHandler().postDelayed(this::sendToAtrialFibrillationSetting, 1000);
            }
        }
    }

    //相关回调
    private void AtrialFibrillationListener() {
        //房颤图的回调
        /*MessageManager.getInstance().setConnectAFListener(afDataResponse -> {
            switch (afDataResponse.getType()) {
                case Constants.MESSAGE_STATE_CHANGE:
                    if (afDataResponse.getStatus() == BluetoothChatService.STATE_CONNECTED) {
                        runOnUiThread(() -> {
                            //toastUtil.showToast("房颤测量准备完成");
                            egc.setVisibility(View.VISIBLE);
                        });
                    }
                    break;
                case Constants.MESSAGE_READ:
                    messageReadStatus = true;
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    if (afDataResponse.getMv() != 0 && afDataResponse.getTimeStamp() != 0) {
                        //显示心电图
                        egc.addPPG(afDataResponse.getMv(), afDataResponse.getTimeStamp());
                    }
                    break;
            }
        });*/

        //房颤测试监听数据回调
        MessageManager.getInstance().setAFListener(hrvBean -> {
            int pip = 0;
            //此处收集相关回调数据，插入数据表中
            LogUtil.e(TAG, "PPI = " + hrvBean.getPpi() + " State = " + hrvBean.getState() + "  UnixTimestamp = " + hrvBean.getUnixTimestamp());
            if (hrvBean.getState() == 255) {
                toastUtil.showToast("测量失败");
                handler.sendEmptyMessage(1);
            } else {
                String[] split = hrvBean.getPpi().split(",");
                for (String aSplit : split) {
                    pip = pip + Integer.valueOf(aSplit);
                }
                dataManager.insertAtrialFibrillationInfo(new AtrialFibrillationInfo(UserContent.UserName, CalenderUtilsClass.getCurrentDay(true), String.valueOf(hrvBean.getState()), String.valueOf(pip)));
                handler.sendEmptyMessage(1);
            }
        });
    }

    private final boolean[] isCollection = {true};
    private int count = 0;

    //房颤图链接
    private void sendToAtrialFibrillationSetting() {
        AppConfigurationInfo appConfigurationInfo = dataManager.queryAppConfigurationInfo(UserContent.UserName);
        if (appConfigurationInfo != null) {
            MessageManager.getInstance().connectAF(appConfigurationInfo.getMAC(), afDataResponse -> {
                if (isFinishing()) {
                    return;
                }
                switch (afDataResponse.getType()) {
                    case Constants.MESSAGE_STATE_CHANGE:
                        if (afDataResponse.getStatus() == BluetoothChatService.STATE_CONNECTED) {
                            Log.e(TAG, "准备完成");
                            isCollection[0] = false;
                            runOnUiThread(() -> {
                                egc.setVisibility(View.VISIBLE);
                                if (mConProgressDialog != null && mConProgressDialog.isShowing()) {
                                    mConProgressDialog.dismiss();
                                }
                            });
                        }
                        break;
                    case Constants.MESSAGE_READ:
                        messageReadStatus = true;
                        isCollection[0] = false;
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (afDataResponse.getMv() != 0 && afDataResponse.getTimeStamp() != 0) {
                            //显示心电图
                            egc.addPPG(afDataResponse.getMv(), afDataResponse.getTimeStamp());
                        }
                        break;
                }
                CommonUtils.getHandler().postDelayed(() -> {
                    if (isCollection[0]) {
                        count++;
                        if (count > 3) {
                            CommonUtils.showToast(getApplicationContext(), "数据加载异常,请重新进入");
                            CommonUtils.getHandler().removeCallbacks(null);
                            finish();
                            return;
                        }
                        try {
                            //MessageManager.getInstance().connectAF(appConfigurationInfo.getMAC(), null);
                            sendToAtrialFibrillationSetting();
                        } catch (Throwable e) {
                            e.printStackTrace();
                            CommonUtils.showToast(getApplicationContext(), "数据加载异常,请重新进入");
                            finish();
                        }
                    }
                }, 3000);
            });
        }
    }

    //心率状态
//    private boolean returnHeartStatus(String content) {
//        boolean status = false;
//        if (getResources().getInteger(R.integer.heart_rate_min) > Integer.valueOf(content) || Integer.valueOf(content) > getResources().getInteger(R.integer.heart_rate_max))
//            status = true;
//        return status;
//    }

    //房颤状态
//    private String returnAtrialFibrillationStatus(int pip) {
//        String status = "正常";
//        if (getResources().getInteger(R.integer.heart_rate_min) > pip || pip > getResources().getInteger(R.integer.heart_rate_max))
//            status = "房颤";
//        return status;
//    }

    @Override
    protected void onDestroy() {
        //MessageManager.getInstance().setConnectAFListener(null);
        super.onDestroy();
    }
}
